package com.sso.server.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.sso.core.conf.SSOConf;
import com.sso.core.exception.SsoException;
import com.sso.core.filter.SsoTokenFilter;
import com.sso.core.store.SsoLoginStore;
import com.sso.core.util.JedisUtil;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;


@Configuration
public class SsoConfig implements InitializingBean, DisposableBean {

    @Value("${sso.redis.address}")
    private String redisAddress;

    @Value("${sso.redis.expire.minute}")
    private int redisExpireMinute;

    @Value("${sso.auth.jdbc.mysql.url}")
    private String mysqlUrl;

    @Value("${sso.auth.jdbc.mysql.user}")
    private String mysqlUser;

    @Value("${sso.auth.jdbc.mysql.password}")
    private String mysqlPass;


    public static String cookieDomain;


    @Value("${sso.cookie.domain}")
    public void setCookieDomain(String cookieDomain) {
        SsoConfig.cookieDomain = cookieDomain;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        SsoLoginStore.setRedisExpireMinute(redisExpireMinute);
        JedisUtil.init(redisAddress);
    }



    @Override
    public void destroy() throws Exception {
        JedisUtil.close();
    }

    @Bean
    public DataSource getDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(mysqlUrl);
        dataSource.setUsername(mysqlUser);
        dataSource.setPassword(mysqlPass);
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        return dataSource;
    }

    @Bean
    public FilterRegistrationBean ssoFilterRegistration() {

        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setName("corsFilter");
        registration.setOrder(1);
        registration.addUrlPatterns("/*");
        registration.setFilter(new CorsFilter());
        return registration;
    }


}
